import io from 'socket.io-client';
import isArray from 'lodash/isArray';
import { logInfo } from './debugger';
import { EventEmitter2 } from 'eventemitter2';

export default class Signal {
    constructor(host = '/', opts = {}, room = './', seedBank) {
        this.emitter = new EventEmitter2();
        this.host = host;
        this.room = room;
        this.opts = opts;
        this.isConnected = false;

        this.socket = io(host, opts);

        this.socket.on('connect', () => {
            this.socket.emit('join', this.room);

            this.socket.on('ready', seeds => {
                this.socket.on('returnPeer', params => {
                    let partName = params.part;
                    if (
                        isArray(params.resources) &&
                        params.resources.length > 0
                    ) {
                        let peerHasPart = params.resources[0];
                        seedBank.returnPeer(partName, peerHasPart);
                    } else {
                        seedBank.returnPeer(partName, null);
                    }
                });

                //signal
                this.socket.on('receiveCandidate', (peer, candidate) => {
                    seedBank
                        .getConnectedPeer(peer)
                        .receiveIceCandidate(candidate);
                    logInfo(`收到来自 ${peer} 的candidate`);
                });

                this.socket.on('receiveOffer', (peer, offer) => {
                    seedBank.getConnectedPeer(peer).receiveOffer(offer);
                    logInfo(`收到来自 ${peer} 连接描述`);
                });

                this.socket.on('receiveAnswer', (peer, answer) => {
                    seedBank.getConnectedPeer(peer).receiveAnswer(answer);
                    logInfo(`收到来自 ${peer} 的应答`);
                });

                logInfo('P2P服务已连接');

                this.isConnected = true;
            });
        });
    }

    addPart(videoId, part, type) {
        if (!this.isConnected) return;
        this.socket.emit('addPart', videoId, part, type);
        logInfo(`添加数据模块信息`);
    }

    getPeer(videoId, part) {
        if (!this.isConnected) return;
        this.socket.emit('getPeer', videoId, part);
        logInfo(`请求拥有模块的peer`);
    }

    //siginal
    sendCandidate(id, candidate) {
        if (!this.isConnected) return;
        this.socket.emit('sendCandidate', id, candidate);
        logInfo(`发送candidate给 ${id}`);
    }

    sendOffer(id, offer) {
        if (!this.isConnected) return;
        this.socket.emit('sendOffer', id, offer);
        logInfo(`发送描述请求给 ${id}`);
    }

    sendAnswer(id, answer) {
        if (!this.isConnected) return;
        this.socket.emit('sendAnswer', id, answer);
        logInfo(`发送描述回复给 ${id}`);
    }

    close() {
        this.socket.disconnect();
        this.isConnected = false;
    }
}
